/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/9/23
 * Time: 23:23
 */
public class Solution {
    private int[] temp;
    public int reversePairs(int[] record) {
        temp = new int[record.length];
        return mergeSort(record,0,record.length - 1);
    }

    private int mergeSort(int[] record, int left, int right) {
        if (left >= right) return 0;
        int mid = (right + left) / 2,ret = 0;
        //[left,mid][mid + 1,right]
        ret += mergeSort(record, left, mid);
        ret += mergeSort(record, mid + 1, right);
        int index = 0,cur1 = left,cur2 = mid + 1;
        while (cur1 <= mid && cur2 <= right) {
            if (record[cur1] <= record[cur2]) {
                temp[index++] = record[cur1++];
            }else {
                ret += mid - cur1 + 1;
                temp[index++] = record[cur2++];
            }
        }
        while (cur1 <= mid) {
            temp[index++] = record[cur1++];
        }
        while (cur2 <= right) {
            temp[index++] = record[cur2++];
        }
        for (int i = left; i <= right; i++) {
            record[i] = temp[i - left];
        }
        return ret;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        int ret = solution.reversePairs(new int[]{9, 7, 5, 4, 6});
        System.out.println(ret);
    }
}
